package com.lh.handler;

import com.lh.util.MyLog;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.NestedRuntimeException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * 全局异常处理配置类
 *
 * @Author LuoHang
 * @Date 2022-05-09 18:07
 *
 * 注解：@ControllerAdvice(annotations = {Controller.class, RestController.class})
 * 参数   basePackages：指定切入的包
 *       annotations：指定使用Controller、RestController注解的类切入
 **/
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {
    /**
     * 处理Controller层发生异常时后续操作
     *
     * 注解：@ExceptionHandler 处理什么类型的异常
     * @param model 数据
     * @param exception Controller层抛出的异常对象
     * @return 视图名称
     */
    @ExceptionHandler(value = Exception.class)
    public String errorHandlerByJson(Model model,Exception exception){
        MyLog.info(GlobalExceptionHandler.class,"发生异常");
        exception.printStackTrace();
        if (exception instanceof ArithmeticException) {
            model.addAttribute("msg","算数异常：" + exception.getMessage());
        } else if (exception instanceof IOException){
            model.addAttribute("msg","IO异常：" + exception.getMessage());
        } else if (exception instanceof NestedRuntimeException ) {
            model.addAttribute("msg","网络异常：" + exception.getMessage());
        }else {
            model.addAttribute("msg",exception.getMessage());
        }
        return "error";
    }

    /**
     * 配置404，401，500等常见异常处理
     * @return webServerFactoryCustomizer
     */
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
        return (factory -> {
            ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED,"/exception/401");
            ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND,"/exception/404");
            ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,"/exception/500");
            factory.addErrorPages(error401Page,error404Page,error500Page);
        });
    }
}
